package com.gxs.ea.fileupload.beans.utils;

import java.io.Serializable;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.gxs.ea.fileportal.domain.BaseCompany;
import com.gxs.ea.fileupload.beans.data.model.User;
import com.gxs.ea.fileupload.beans.data.service.CompanyService;

@Component
public class AuthUtils implements Serializable
{
	@Autowired
	private CompanyService companyService;
	
	public AuthUtils()
	{
		
	}
	
	public User getDetailsForLoggedInUser()
	{
		User user = new User();
		String userName = SecurityContextHolder.getContext().getAuthentication().getName();
		Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();

		user.setUsername(userName);
		user.setAuthorities(authorities);
		
		BaseCompany selectedCompany = null;
		
		if(userName.equalsIgnoreCase("admin"))
		{
			selectedCompany = new BaseCompany(true);
			selectedCompany.setCompanyCity("Gaithersburg");
			selectedCompany.setCompanyCountry("United States");
			selectedCompany.setCompanyName("GXS Inc");
			selectedCompany.setCompanyCode("gxs");
			
			user.setCompanyCode("gxs");
			user.setCompany(selectedCompany);
		}
		else if(userName.indexOf("-") < 1)
		{
			user.setCompany(null);
			user.setCompanyCode(null);
		}
		else
		{
			String companyCode = userName.substring(userName.lastIndexOf("-")+1);
			selectedCompany = companyService.findByCompanyCode(companyCode);

			user.setCompanyCode(companyCode);
			user.setCompany(selectedCompany);
			
			// it can be null. we are going to reutrn null if it is. 
		}


		return user;

	}

}
